export default defineNuxtPlugin((nuxtApp) => {
  const userStore = useUserStore();
  const token = userStore.token;
  const config = useRuntimeConfig();
  const api = $fetch.create({
    baseURL: config.public.apiBaseUrl,
    onRequest({ request, options, error }) {
      if (token) {
        // 请注意，这依赖于 ofetch >= 1.4.0 - 可能需要刷新您的锁文件
        options.headers.set("token", token);
      }
    },
    onResponse({ response }) {
      // 处理通用响应逻辑
    },
    async onResponseError({ response }) {
      if (response.status === 401) {
        await nuxtApp.runWithContext(() => navigateTo("/login"));
      }
    },
  });

  // 暴露给 useNuxtApp().$api
  return {
    provide: {
      api,
    },
  };
});
